/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net.cjb.malacma.rssfeed.persistence;


import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.hibernate.ejb.Ejb3Configuration;

/**
 *
 * @author malacma
 */
public class GenericPersistence {

    private static final EntityManagerFactory entityManagerFactory;
    private static final Ejb3Configuration configuration;
    private static final ThreadLocal<EntityManager> entityManagerThreadLocal = new ThreadLocal<EntityManager>();

    static {
        configuration = new Ejb3Configuration().configure("PinoRSSPU", null);
        entityManagerFactory = configuration.buildEntityManagerFactory();
    }

    public static final EntityManager getEntityManager() {
        if (entityManagerThreadLocal.get() == null) {
            EntityManager entityManager = entityManagerFactory.createEntityManager();
            entityManagerThreadLocal.set(entityManager);
        }

        return entityManagerThreadLocal.get();
    }
    public static void closeEntityManager() {
        EntityManager entityManager = entityManagerThreadLocal.get();
        if (entityManager != null && entityManager.isOpen()) {
            entityManager.close();
        }

        entityManagerThreadLocal.set(null);
    }
}
